import {OrderApi, ShopApi} from "@/api/user";
import createLoadMoreStore from "@/store/components/loadMore";
import _ from "underscore"

let listStore = createLoadMoreStore();

export default {
    namespaced: true,
    state: {
        shopId: "",
        shopInfo: {
            logo: "",
            name: ""
        },
        goodsList: [],
        shopDetails: {},
    },
    mutations: {
        setShopInfo(state, {logo, name}) {
            state.shopInfo = {
                logo, name
            }
        },
        setGoodsList(state, list) {
            state.goodsList = list;
        },
        setShopId(state, id) {
            state.shopId = id;
        }
    },
    actions: {
        async fetchShopDetails({state, commit}) {
            let Rs = await ShopApi.getShopDetails({
                id: state.shopId
            })
            if (Rs.code === 200) {
                const {logo, name} = Rs.data.shop;
                commit("setShopInfo", {
                    logo, name
                })
            }
        },
        async fetchList({dispatch, state, getters}, p = 1) {
            return dispatch("list/fetchListData", {
                opt: {
                    pageNum: p, pageSize: 10,
                    shopId: state.shopId
                },
                next: false,
                api: ShopApi.getProductList
            })
        },
        async fetchNextData({dispatch, state}) {
            return dispatch("list/fetchListData", {
                opt: {
                    pageSize: 5,
                    shopId: state.shopId
                },
                next: true,
                api: ShopApi.getProductList,
            })
        },
    },
    modules: {
        list: {
            namespaced: true,
            state: {...listStore.state},
            mutations: {...listStore.mutations},
            actions: {...listStore.actions}
        }
    },
    getters: {
        productList(state) {
            return _.map(state.list.items, item => {
                return {
                    ...item,
                    key: `${item.shop_id}-${item.id}`
                }
            })
        },
    }
};
